<template>
  <div class="custom-anchor">
    <!-- 渲染原生 el-anchor 组件 -->
    <el-anchor
      ref="anchorRef"
      :offset="offset"
      :bounds="bounds"
      :direction="direction"
      :container="container"
      :marker-class="markerClass"
      @change="handleAnchorChange"
    >
      <!-- 动态渲染所有插槽内容 -->
      <template v-for="(link, index) in normalizedLinks" :key="index">
        <el-anchor-link
          :href="generateHref(link.href)"
          :title="link.title"
          @click.prevent="handleLinkClick(link.href, $event)"
          style="padding-left: 0 !important;"
        />
      </template>
      <slot></slot>
    </el-anchor>
  </div>
</template>

<script setup>
import { ref, computed, useSlots, onMounted } from 'vue'
import { useRouter } from 'vue-router'

const props = defineProps({
  // 接收 Element Plus Anchor 的所有 props
  offset: { type: Number, default: 0 },
  bounds: { type: Number, default: 5 },
  direction: { type: String, default: 'vertical' },
  container: { type: String, default: '' },
  markerClass: { type: String, default: '' },
  // 自定义 props
  links: { type: Array, default: () => [] } // [{href: '#section1', title: 'Section 1'}]
})

const emit = defineEmits(['change'])

const router = useRouter()
const slots = useSlots()
const anchorRef = ref(null)

// 合并 props.links 和插槽中的链接
const normalizedLinks = computed(() => {
  const slotLinks =
    slots
      .default?.()
      .filter((node) => node.type.name === 'ElAnchorLink')
      .map((node) => ({
        href: node.props?.href,
        title: node.props?.title
      })) || []

  return [...props.links, ...slotLinks]
})

// 在 hash 模式下生成正确的 href
const generateHref = (href) => {
  if (!href) return ''
  // 如果已经是完整路径则直接返回
  if (href.startsWith('http') || href.startsWith('/')) return href

  const currentPath = router.currentRoute.value.path
  return `${currentPath}${currentPath.endsWith('/') ? '' : '/'}${href}`
}

// 处理锚点点击
const handleLinkClick = (href, event) => {
  if (!href || href.startsWith('http')) return

  const hash = href.replace('#', '')
  const element = document.getElementById(hash)

  if (element) {
    // 平滑滚动到目标元素
    element.scrollIntoView({ behavior: 'smooth' })

    // 更新 URL hash (兼容 vue-router)
    const newHash = `#/${hash}`
    if (window.location.hash !== newHash) {
      window.history.pushState(null, '', newHash)
    }

    // 手动触发锚点变化事件
    // if (anchorRef.value) {
    //   anchorRef.value.setActiveLink(href)
    // }
  }
}

// 处理锚点变化事件（过滤掉 vue-router 的 hash）
const handleAnchorChange = (newLink) => {
  console.log('newLink', newLink)
  if (newLink && newLink.href) {
    emit('change', {
      ...newLink,
      href: newLink.href.replace(/^#\//, '#') // 转换回普通锚点格式
    })
  }
}

// 初始化时处理当前 hash
onMounted(() => {
  const handleInitialHash = () => {
    const currentHash = window.location.hash
    if (currentHash && currentHash.startsWith('#/')) {
      const cleanHash = currentHash.replace('#/', '')
      handleLinkClick(`#${cleanHash}`, null)
    }
  }

  // 立即执行一次
  handleInitialHash()

  // 监听 hash 变化
  window.addEventListener('hashchange', handleInitialHash)
})
</script>

<style scoped>
.custom-anchor {
  /* 可以根据需要添加样式 */
}
</style>
